<template>
  <el-space v-loading="loading" class="pro-table" direction="vertical">
    <!-- 头部 -->
    <div class="pro-table__header">
      <el-space>
        <el-button type="default" @click="refresh">刷新</el-button>
        <slot name="tool" />
      </el-space>

      <el-space>
        <el-input clearable placeholder="搜索关键字" />
        <el-button type="primary">搜索</el-button>
      </el-space>
    </div>
    <!-- 表格主体 -->
    <div class="pro-table__body">
      <el-table
        border
        :data="rows"
        :default-sort="{ prop: query.prop, order: query.order }"
        @sort-change="handleSortChange"
      >
        <slot />
      </el-table>
    </div>
    <!-- 表格分页 -->
    <div class="pro-table__footer">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :default-current-page="query.currentPage"
        :default-page-size="query.pageSize"
        :total="total"
        @change="handlePaginationChange"
      />
    </div>
  </el-space>
</template>

<script>
export default {
  name: "ProTable",

  props: {
    // 请求表格数据的函数
    request: {
      type: Function,
      required: true,
    },
    // 是否默认触发接口的调用
    isAuto: {
      type: Boolean,
      default: true,
    },
    // 默认当前页
    defaultCurrentPage: {
      type: Number,
      default: 1,
    },
    // 默认每页显示条数
    defaultPageSize: {
      type: Number,
      default: 5,
    },
    // 默认的排序方式与规则
    defaultSort: {
      type: Object,
      default: () => ({
        prop: "",
        order: "",
      }),
    },
  },

  data() {
    return {
      loading: false, // 请求中
      total: 1, // 数据总条数
      rows: [], // 表格行数据

      query: {
        currentPage: this.defaultCurrentPage,
        pageSize: this.defaultPageSize,
        prop: this.defaultSort.prop,
        order: this.defaultSort.order,
      },
    };
  },

  methods: {
    /**
     * 刷新数据的函数
     */
    async refresh() {
      try {
        this.loading = true;
        // 调用 request prop
        const { list, total } = await this.request(this.query);
        this.rows = list;
        this.total = total;
      } finally {
        this.loading = false;
      }
    },

    /**
     * 处理分页的currentPage与pageSize变化的事件
     */
    handlePaginationChange(currentPage, pageSize) {
      console.log("handlePaginationChange", currentPage, pageSize);
      // 修改 query 内容
      this.query.currentPage = currentPage;
      this.query.pageSize = pageSize;

      // 重新调用 refresh
      this.refresh();
    },

    /**
     * 处理表格排序
     */
    handleSortChange({ order, prop }) {
      // 修改 query 内容
      this.query.order = order;
      this.query.prop = prop;

      // 重新调用 refresh
      this.refresh();
    },
  },

  created() {
    this.isAuto && this.refresh();
  },
};
</script>

<style scoped>
.pro-table__header {
  display: flex;
  justify-content: space-between;
}

.pro-table__footer {
  display: flex;
  justify-content: flex-end;
}
</style>
